package com.hr.mes.config;

import com.hr.mes.dto.JWTToken;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class JWTFilter extends BasicHttpAuthenticationFilter {

    @Override
    protected boolean isLoginAttempt(ServletRequest request, ServletResponse response) {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        return authorization!=null&&authorization.startsWith("Bearer ");
    }

    @Override
    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = httpServletRequest.getHeader("Authorization").substring(7);
        JWTToken jwt = new JWTToken(token);
        //JWTFilter的getSubject(request, response).login(jwt)会执行JWTRealm的doGetAuthenticationInfo方法
        getSubject(request, response).login(jwt);
        return true;
    }
}
